local core = require("core")

local plugin_name = "filter"
local log = core.log.new(plugin_name..": ")
local app_config = require("conf.config").get(plugin_name)
local plugin_config = require("conf.config").get_plugin(plugin_name)
local request_matcher = require "plugins.filter.request_matcher".new()
local template = require "plugins.common.template"
local status_code = app_config["status_code"];
local msg = app_config["msg"]

-- optional 是否可选
local _M = {
    name = plugin_name,
    desc = "attack filter",
    optional = false,
    version = "v1.0"
}

--function _M.do_in_init()
--    --log.notice("do_in_init")
--    -- body
--end
--
--function _M.do_in_init_worker()
--    --log.info("do_in_init_worker")
--    -- body
--end

--function _M.do_in_rewrite()
--    --log.notice("do_in_rewrite")
--    --log.error("do_in_rewrite")
--    -- body
--end

function _M.do_in_access()
    --log.error(enable == true and request_matcher.test(matcher) == true)
    for _,rule in ipairs(plugin_config) do
        local enable = rule['enable']
        local matcher = rule['matchers']

        if enable == true and request_matcher:test(matcher) == true then
            log.notice( "Access Deny")
            if app_config["debug_model"] == true then
                return;
            end

            --return template:render("common","access_deny",status_code)
            return template:render(msg,status_code)
        end
    end

end

--function _M.do_in_content()
--    --log.notice("do_in_content")
--    -- body
--end
--
--function _M.do_in_balancer()
--    --log.notice("do_in_balancer")
--    -- body
--end
--
--function _M.do_in_body_filter()
--    --log.error("do_in_body_filter")
--    -- body
--end
--
--function _M.do_in_log()
--    --log.error("do_in_log")
--    -- body
--end

setmetatable(_M,{
    __tostring = function(self)
        return self.name
    end
})

return _M
